const mongoose = require('mongoose');
const winston = require('../utils/winstonLogger.js');
const customerModel = mongoose.model('Customer');


module.exports = {
    login: login,
    register: register,
    updateInfo : updateInfo,
    findCustomerById : findCustomerById
}

function login($n = {}, callback) {
    customerModel.find($n, function (err, doc) {
        if (err) {
            winston.error(err);
            callback(err, null);
        } else {
            var user={
                username : doc[0].username,
                id : doc[0]._id
            }
            console.log('login....'+user.id);
            callback(null, user);
        }
    });
}



function register(customer, callback) {
    
        customerModel.findOne({ username: customer.username }, function (err, result) {
            console.log(result);
            if (result == null) {
                var c = new customerModel(customer);
                c.name = customer.username;
                c.save(function (err, doc) {
                    if (err) {
                        winston.error(err);
                        callback(err, null);
                    } else {
                        callback(null, doc);
                    }
                });
            }else{
                var r = {
                    username:result.username,
                    name:result.name,
                    phone:result.phone,
                    flag:1
                };
                // r.flag = 1;
                // result.flag = 1;
                console.log(r);
                callback(null,r);
            }
        });
    }
    
    


function updateInfo(customer,callback){
    customerModel.updateMany({_id:customer._id},customer,function(err,doc){
        if(err){
            winston.error(err);
            callback(err,null);
        }else{
            console.log(doc);
            callback(null,doc);
        }
    }); 
}


function findCustomerById(customerId,callback){
customerModel.findOne({_id:customerId},function(err,result){
    if(err){
        winston.error(err);
        callback(err,null);
    }else{
        console.log(result);
        callback(null,result);
    }
});
}
